<?php
declare (strict_types = 1);

namespace app\user\model;

use app\common\model\BaseModel;
use think\Model;

/**
 * @mixin \think\Model
 */
class District extends BaseModel
{
    public $page = '';//分页数据
    public $count = '';//数据总数
    public $error = '';//报错
    public $field = 'id,pid,name,sort,level';

    // 获取数据
    public function getList()
    {
        $this->setSrConfig([
            'field' => $this->field,
            //'where' => ['is_show' => 1]
        ]);
        return $this->getListCache();
    }


    /**
     * @param $listArrs 传入的地址的id
     * @return array  返回对应的省市区
     */
    public function getAddressStr($listArrs){
        $whereIn = [$listArrs['province'],$listArrs['city'],$listArrs['area']];
        $province =  $this::whereIn('id',$whereIn)->select()->toArray();
        if($province && count($province) == 3){
            $province[0]['name'] = $province[0]['name']."省";
            $province[1]['name'] = $province[1]['name']."市";
            $province[2]['name'] = $province[2]['name']."区";
            return [
                'province' => $province[0]['name'],
                'city' => $province[1]['name'],
                'area' => $province[2]['name']
            ];
        }
        return [false,false,false];
    }


    //根据id获取省、市、区号
    public function getAllCode($id,$lng){
        if(empty($id)) return [];
        $level = [
            1=>'province',
            2=>'city',
            3=>'area',
            4=>'street',
        ];
        $ret = [
            'province'=>0,
            'city'=>0,
            'area'=>0,
            'street'=>0,
        ];
        $where = ['is_delete'=>0];
        if(!empty($id)) $where['pid'] = $id;
        $street = $this->field('id,name,lng,lat,pid,(st_distance (point (lng, lat),point('.explode(',',$lng)[0].','.explode(',',$lng)[1].') ) / 0.0111) AS distance')->where($where)->order('distance')->find();
        if(!empty($street)) $ret['street'] = $street['id'];
        if(empty($id)) $id = $street['pid'];
        rest:
        $info = $this->where(['id'=>$id,'is_delete'=>0])->find()->toArray();
        if(isset($level[$info['level']])) $ret[$level[$info['level']]] = $info['id'];
        if(!empty($info['pid'])){
            $id = $info['pid'];
            goto rest;
        }
        return $ret;
    }
}
